package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.ContentUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.uis.activitys.BaseActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.ScreenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements View.OnLayoutChangeListener {

    private static final String TAG = LoginActivity.class.getSimpleName();
    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.forget_pwd)
    TextView forgetPwd;
    @BindView(R.id.txt_buy_im)
    TextView txt_buy_im;
//    @BindView(R.id.login_logo)
//    ImageView logo;

//    @BindView(R.id.country)
//    TextView country;
    @BindView(R.id.activity_login)
    LinearLayout linearlayout ;
    @BindView(R.id.linear_login)
    LinearLayout linearLogin;
    @BindView(R.id.divide_phone)
    View divide_phone;
    @BindView(R.id.divide_pass)
    View divide_pass;

    private int CAMERA_JAVA_REQUEST_CODE = 5;

    public static final int REGISTER = 2;
    public static final int REQUEST_COUNTRY = 1000;
    private static final int SDK_PERMISSION_REQUEST = 127;
    private PGService mPgService;
    private String countryStr;
    private String mobileCode = "+86";
    private String permissionInfo;
    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        countryStr = getString(R.string.chain);
        initEditView();
//        GlideUtils.loadLocalImage(this, R.drawable.logo, logo);
        mPgService = PGService.getInstance();
        EventBus.getDefault().register(this);
        String toast = getIntent().getStringExtra("toast");
        if (toast != null) {
            Toast.makeText(this,toast,Toast.LENGTH_LONG).show();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           // requestSomePower();
        }
//        country.setText(countryStr + " （" + mobileCode + "）");
       // linearlayout.addOnLayoutChangeListener(this);
       // controlKeyboardLayout(linearlayout,login);
    }

    private void initEditView(){
        userName.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
// 此处为得到焦点时的处理内容
                    divide_phone.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                } else {
// 此处为失去焦点时的处理内容
                    divide_phone.setBackgroundColor(getResources().getColor(R.color.black_divider));
                }
            }
        });
        password.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
// 此处为得到焦点时的处理内容
                    divide_pass.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                } else {
// 此处为失去焦点时的处理内容
                    divide_pass.setBackgroundColor(getResources().getColor(R.color.black_divider));
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        UserEntivity userEntivity = ToolsUtils.getUser();
        if (userEntivity != null) {
            userName.setText(userEntivity.getMobile());
            password.setText(userEntivity.getPassword());
//            password.setInputType(InputType.TYPE_CLASS_TEXT);
        }
    }
    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            //地理位置权限
            if (addPermission(permissions,Manifest.permission.ACCESS_FINE_LOCATION)){
                permissionInfo +="Manifest.permission.ACCESS_FINE_LOCATION Deny \n";
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }
    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }
    /**
     * 获取权限
     */
    private void requestSomePower() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                &&
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_JAVA_REQUEST_CODE);
        }
    }

    @OnClick({R.id.register, R.id.forget_pwd, R.id.login, R.id.country, R.id.txt_buy_im})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register:
                password.setText("");
                userName.setText("");
                startActivity(RegisterActivity.class);
                break;
            case R.id.forget_pwd:
                password.setText("");
                userName.setText("");
                Bundle bundle = new Bundle();
                bundle.putInt("tag",1);
                startActivity(NewPasswordActivity.class,bundle);
                break;
            case R.id.login:
                String mobileStr = userName.getText().toString().trim();
                String pwdStr = password.getText().toString().trim();
                if ("".equals(mobileStr) || "".equals(pwdStr)) {
                    showToast(getResources().getString(R.string.please_import_right_phone_and_psd));
                } else {
                    /*if (pwdStr.length() > 15){
                        showToast("密码不能大于15位");
                        return;
                    }*/
                    ToolsUtils.doLogin(mPgService, mobileCode, LoginActivity.this, mobileStr, pwdStr);
                }
                break;
            case R.id.country :
                startActivityForResult(CountrySelectActivity.class, REQUEST_COUNTRY);
                break;
            case R.id.txt_buy_im :
                startActivity(LiangSelecterSortActivity.class);
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(ImMessage imMessage){
        if (imMessage.getMessageType()== Constant.MESSAGE_TYPR_OTHER_LOGIN){
            ToolsUtils.showToast(this,getResources().getString(R.string.other_clien_login));
        }
        if (imMessage.getMessageType()== Constant.MSG_OF_FREEZE){
            ToolsUtils.showToast(this,getResources().getString(R.string.account_is_frozen));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCode(String code){
        Log.i("info","code=="+code);
        switch (code){
            case "1" :
                ToolsUtils.doLogin(mPgService, mobileCode, this, ToolsUtils.getUser().getMobile(), ToolsUtils.getUser().getPassword());
                break ;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return false;
    }

    /**
     * 调用Activity 后 返回值处理
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_COUNTRY:
                    countryStr = data.getStringExtra("country");
                    mobileCode = data.getStringExtra("mobileCode");
//                    country.setText(countryStr + " （" + mobileCode + "）");
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
        if (ContentUtils.getScreenHeight(this) / 4 < (ContentUtils.getScreenHeight(this) - i3)) {
            Log.i("info", "弹出键盘");
           linearLogin.scrollTo(0, ScreenUtil.dp2px(30));
        }
    }
   /* *//**
     * @param root         最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     *//*
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
                .OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
               // KLog.e("BEGIN");
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                   // KLog.e("SHENGD");
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                   // KLog.e(location[1] + "");
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    if (srollHeight != 0) {
                        root.scrollTo(0, srollHeight);
                    }

                } else {
                    //键盘隐藏
                   // KLog.e("THRESS");
                    root.scrollTo(0, 0);
                }
            }
        });
    }*/
}
